<?php
namespace App\Http\Controllers\MobileWeb;

use App\Http\Controllers\WebController;
use App\Http\Controllers\Business\App\Common\Common;
use App\Http\Controllers\Business\App\PublicBusiness;
use App\Http\Controllers\Business\App\Auth\AppAuth;
use App\Http\Controllers\Business\App\MyCenter\MyCenter;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Support\Facades\Cookie;

class MyCenterController extends WebController
{
    //首页
    public function index() {
        $user = Auth::user();
        $userId = $user->id;
        $wxOpenId = $user->wxopenid;
        $result = MyCenter::index($userId);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $data = $result['data'];
        $nickName = $data['nickname'];
        if(is_numeric($nickName) && (strlen($nickName) == 11)) {
            $nickName = str_replace(substr($nickName, 3, 4), '****', $nickName);
        }
        $data['nickname'] = $nickName;
        if(!strstr($data['avatar'], 'http')) {
            $data['avatar'] = env('IMAGE_DOMAIN') . $data['avatar'];
        }
        $data['wxopenid'] = $wxOpenId;
        $parentId = PublicBusiness::encrypt($userId, 'E', '');
        //$parentId = urlencode($parentId); //url编码
        $parentId = rawurlencode($parentId);
        $data['recommendurl'] = '/mobile/mycenter/recommend?parentid=' . $parentId . '&avatar=' . $data['avatar'] . '&nickname=' . $data['nickname'];
        return view('mobile.mycenter.index', $data);
    }
    //个人信息
    public function getUserInfo() {
        $userId = Auth::id();
        $userInfoResult = MyCenter::getUserInfo($userId);
        if($userInfoResult['status'] == 'failed') {
            return view('errors.404');
        }
        $data = $userInfoResult['data'];
        if(!strstr($data['avatar'], 'http')) {
            $data['avatar'] = env('IMAGE_DOMAIN') . $data['avatar'];
        }
        return view('mobile.mycenter.user_info', $data);
    }
    //保存个人信息
    public function saveUserInfo() {
        $userId = Auth::id();
        $nickName = $this->request->get('nickname');
        $birthday = $this->request->get('birthday');
        $sex = $this->request->get('sex');
        if(Cookie::has('cityname')) {
            $cityName = Cookie::get('cityname');
        } else {
            $cityName = '';
        }
        if($sex == '男') {
            $sex = '1';
        } elseif($sex == '女') {
            $sex = '2';
        } else {
            $sex = '0';
        }
        $result = MyCenter::saveUserInfo($userId, $nickName, $sex, $birthday, $cityName);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    public function saveAvatar() {
        $userId = Auth::id();
        $avatar = $this->request->get('avatar');
        $result = MyCenter::saveUserAvatar($userId, $avatar);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //更多
    public function more() {
        return view('mobile.mycenter.more');
    }
    //新用户指导
//    public function newUserGuide() {
//        return view('mobile.mycenter.new_user_guide');
//    }
    //如何设置支付密码
    public function howPayPassword() {
        return view('mobile.mycenter.how_pay_password');
    }
    //如何使用翻贝网买单
    public function AppUse() {
        return view('mobile.mycenter.App_use');
    }
    //怎么注册和登录翻贝网账号
    public function AppLogin() {
        return view('mobile.mycenter.App_login');
    }
    //怎么开通订阅提醒
    public function openSubscribe() {
        return view('mobile.mycenter.open_subscribe');
    }
    //如何更换手机号码
    public function changeMobile() {
        return view('mobile.mycenter.change_mobile');
    }
    //用户须知
    public function userKnow() {
        return view('mobile.mycenter.user_know');
    }
    //翻倍券
    public function doubleCoupon() {
        $userId = Auth::id();
        $result = MyCenter::doubleCouponsList($userId);
        if($result['status'] == 'failed') {
            $lists = [];
        }  else {
            $lists = $result['data'];
        }
        $availableLists = [];
        $historyLists = [];
        foreach($lists as $list) {
            $status = $list['status'];
            if($status == '0') {
                array_push($availableLists, $list);
            } else {
                array_push($historyLists, $list);
            }
        }
        $userResult = MyCenter::getUserInfo($userId);
        if($userResult['status'] == 'failed') {
            $recommendUrl = '';
        } else {
            $userData = $userResult['data'];
            $recommendUrl = env('WEB_URL') . '/mobile/mycenter/recommend?id=' . $userId. '&avatar=' .$userData['avatar'] . '&nickname=' . $userData['nickname'];
        }
        $data = [
            'availablelists' => $availableLists,
            'historylists' => $historyLists,
            'recommendurl' => $recommendUrl,
        ];
        return view('mobile.mycenter.double_coupon', $data);
    }
    //红包
    public function redEnvelope() {
        $userId = Auth::id();
        $result = MyCenter::redEnvelopesList($userId);
        if($result['status'] == 'failed') {
            $lists = [];
        }  else {
            $lists = $result['data'];
        }
        $availableLists = [];
        $historyLists = [];
        foreach($lists as $list) {
            $status = $list['status'];
            if($status == '0') {
                array_push($availableLists, $list);
            } else {
                array_push($historyLists, $list);
            }
        }
        $data = [
            'availablelists' => $availableLists,
            'historylists' => $historyLists
        ];
        return view('mobile.mycenter.red_envelope', $data);
    }
    //我的收藏
    public function collection() {
        $userId = Auth::id();
        $collectionListResult = MyCenter::collectionList($userId);
        if($collectionListResult['status'] == 'failed') {
            $lists = [];
        } else {
            $lists = $collectionListResult['data'];
        }
        $data = [
            'lists' => $lists
        ];
        return view('mobile.mycenter.collection', $data);
    }
    //添加收藏
    public function addCollection() {
        $userId = Auth::id();
        $shopId = $this->request->get('shopid');
        $result = MyCenter::addCollection($userId, $shopId);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //删除收藏
    public function deleteCollection() {
        $userId = Auth::id();
        $shopId = $this->request->get('shopid');
        $result = MyCenter::delCollectionByShopId($userId, $shopId);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //我的订阅
    public function subscription() {
        $userId = Auth::id();
        $subscriptionListResult = MyCenter::subscriptionList($userId);
        if($subscriptionListResult['status'] == 'failed') {
            $lists = [];
        } else {
            $lists = $subscriptionListResult['data'];
        }
        $data = [
            'lists' => $lists
        ];
        return view('mobile.mycenter.subscription', $data);
    }
    //添加订阅
    public function addSubscription() {
        $userId = Auth::id();
        $shopId = $this->request->get('shopid');
        $result = MyCenter::addSubscription($userId, $shopId);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //删除订阅
    public function deleteSubscription() {
        $userId = Auth::id();
        $shopId = $this->request->get('shopid');
        $result = MyCenter::delSubscriptionByShopid($userId, $shopId);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }

    //账号安全
    public function accountSecurity() {
        $userId = Auth::id();
        $userInfoResult = MyCenter::getUserInfo($userId);
        if($userInfoResult['status'] == 'failed') {
            return view('errors.404');
        }
        $data = $userInfoResult['data'];
        $mobile = $data['mobile'];
        $mobile = str_replace(substr($mobile, 3, 4),'****', $mobile);
        $data['mobile'] = $mobile;
        return view('mobile.mycenter.account_security', $data);
    }
    //手机绑定
    public function phoneBinding() {
        $user = Auth::user();
        $mobile = $user->mobile;
        $mobile = str_replace(substr($mobile, 3, 4),'****', $mobile);
        $data = [
            'mobile' => $mobile
        ];
        return view('mobile.mycenter.phone_binding', $data);
    }
    //手机绑定时，给手机发送短信（原手机号码, 新手机号码）, type:old表示为给旧手机号码发送，new表示给新手机号码发送
    public function getCaptchaForPhoneUpdated(){
        $mobile = $this->request->get('mobile');
        if ($this->request->has('type') && $this->request->get('type') == 'old') {
            $user = Auth::user();
            if($mobile != $user->mobile) {
                return $this->responseError('原手机号码输入错误');
            }
            $result = AppAuth::getCode($mobile, '1', '1');
            if ($result['status'] == 'failed') {
                return $this->responseError($result['message']);
            }
            $message = $result['message'];
            return $this->responseSuccessMessage($message);
        } else {
            $result = AppAuth::getCode($mobile, '1', '1');
            if ($result['status'] == 'failed') {
                return $this->responseError($result['message']);
            }
            $message = $result['message'];
            return $this->responseSuccessMessage($message);
        }
    }
    //验证手机验证码（绑定手机号）
    public function verifyCaptchaForPhoneUpdated() {
        $mobile = $this->request->get('mobile');
        $code = $this->request->get('code');
        $result = AppAuth::validataSmsCode($mobile, $code);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //确定绑定手机
    public function updatePhone() {
        $oldMobile = $this->request->get('old_mobile');
        $newMobile = $this->request->get('new_mobile');
        $newCode = $this->request->get('new_code');
        $userId = Auth::id();
        $result = MyCenter::updateMobile($userId, $oldMobile, $newMobile, $newCode);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //身份认证
    public function accountAuth() {
        if($this->request->has('type') && ($this->request->get('type') == 'resetpaypassword')) {
            $data = [
                'type' => 'resetpaypassword',
                'realname' => '',
                'identitycard' => '',
            ];
        } else {
            $user = Auth::user();
            $userId = $user->id;
            $userInfoResult = MyCenter::getUserInfo($userId);
            if ($userInfoResult['status'] == 'failed') {
                return view('errors.404');
            }
            $data = $userInfoResult['data'];
            $data['type'] = '';
        }
        return view('mobile.mycenter.account_auth', $data);
    }
    //保存实名认证
    public function saveIdentity() {
        $user = Auth::user();
        $userId = $user->id;
        $message = '';
        if($this->request->has('realname')){
            $realName = $this->request->get('realname');
            $identityCard = $this->request->get('identitycard');
            $saveIdentityResult = MyCenter::saveIdentity($userId, $realName, $identityCard);
            if($saveIdentityResult['status'] == 'success') {
                return redirect()->to('/mobile/mycenter/account/security');
            } else {
                $message = $saveIdentityResult['message'];
            }
        }
        $userInfoResult = MyCenter::getUserInfo($userId);
        if ($userInfoResult['status'] == 'failed') {
            return view('errors.404');
        }
        $data = $userInfoResult['data'];
        $data['message'] = $message;
        return view('mobile.mycenter.account_auth', $data);
    }
    //实名校正
    public function verifyIdentity() {
        $userId = Auth::Id();
        $message = '';
        if($this->request->has('realname')){
            $realName = $this->request->get('realname');
            $identityCard = $this->request->get('identitycard');
            $saveIdentityResult = MyCenter::verifyIdentity($userId, $realName, $identityCard);
            if($saveIdentityResult['status'] == 'success') {
                $url = '/mobile/mycenter/password/set?type=identity_pass&realname=' . $realName. '&identitycard='. $identityCard;
                return redirect()->to($url);
            } else {
                $message = $saveIdentityResult['message'];
            }
        }
        $userInfoResult = MyCenter::getUserInfo($userId);
        if ($userInfoResult['status'] == 'failed') {
            return view('errors.404');
        }
        $data = $userInfoResult['data'];
        $data['message'] = $message;
        return view('mobile.mycenter.account_auth', $data);
    }
    //支付密码
    public function payPassword() {
        $user = Auth::user();
        $payPassword = $user->paypassword;
        $realName = $user->realname;
        $identityCard = $user->identitycard;
        if($payPassword == '') {
            $payPassword = 0;
        } else {
            $payPassword = 1;
        }
        if($realName && $identityCard) {
            $isIdentity = 1;
        } else {
            $isIdentity = 0;
        }
        $data = [
            'paypassword' => $payPassword,
            'isidentity' => $isIdentity
        ];
        return view('mobile.mycenter.pay_password', $data);
    }
    //设置支付密码
    public function setPayPassword() {
        $type = $this->request->get('type');
        if($type == 'delete') {
            $data = [
                'title' => "验证原密码",
                'message' => '',
                'type' => 'delete'
            ];
        } elseif($type == 'add') {
            $data = [
                'title' => "创建支付密码",
                'message' => '创建支付密码(6位的数字)',
                'type' => 'add'
            ];
        } elseif($type == 'update_old') {
            $data = [
                'title' => "验证原密码",
                'message' => '验证原支付密码(6位的数字)',
                'type' => 'update_old'
            ];
        } elseif ($type == 'update_new') {
            $oldPayPassword = $this->request->get('oldpaypassword');
            $data = [
                'title' => "设置新密码",
                'message' => '设置新的支付密码(6位的数字)',
                'type' => 'update_new',
                'oldpaypassword' => $oldPayPassword
            ];
        } elseif($type == 'identity_pass') {
            $realName = $this->request->get('realname');
            $identitycard = $this->request->get('identitycard');
            $data = [
                'title' => '创建支付密码',
                'message' => '创建支付密码(6位的数字)',
                'type' => 'identity_pass',
                'realname' => $realName,
                'identitycard' => $identitycard
            ];
        } else {
            $data = [
                'title' => '创建支付密码',
                'message' => '创建支付密码(6位的数字)',
                'type' => ''
            ];
        }
        return view('mobile.mycenter.password_set', $data);
    }
    //验证支付密码
    public function verifyPayPassword() {
        $userId = Auth::id();
        if(!$this->request->has('paypassword') || !$this->request->has('type')) {
            return $this->responseError('请求的参数不对');
        }
        $payPassword = $this->request->get('paypassword');
        $type = $this->request->get('type');
        if($type == 'add') {
            $result = MyCenter::setPayPassword($userId, $payPassword);
        } elseif($type == 'delete') {
            $result = MyCenter::delPayPassword($userId, $payPassword);
        } elseif($type == 'update_old') {
            $result = MyCenter::validataPayPassword($userId, $payPassword);
        } elseif($type == 'update_new') {
            $oldPayPassword = $this->request->get('oldpaypassword');
            $result = MyCenter::updatePayPasswordForOldPayPassword($userId, $oldPayPassword, $payPassword);
        } elseif($type == 'identity_pass') {
            $realName = $this->request->get('realname');
            $identityCard = $this->request->get('identitycard');
            $result = MyCenter::updatePayPasswordForValidataIdentity($userId, $realName, $identityCard, $payPassword);
        } else {
            return $this->responseError('无效类型');
        }
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage('操作成功');
        }
    }
    //充值支付密码
    public function resetPayPassword() {
        return view('mobile.mycenter.password_reset');
    }
    //推荐有奖
    public function recommend() {
        $avatar = $this->request->get('avatar');
        $userId = $this->request->get('parentid'); //传过来之前就要加密
        $nickName = $this->request->get('nickname');
        $userAgent = $this->request->header('user-agent');
        $platform = PublicBusiness::getPlatformByUserAgent($userAgent);
        $userId = urlencode($userId);
        $inviteUrl = env('WEB_URL') . "/mobile/share/recommend?parentid=". $userId;
        if($avatar != '') {
            if(!strstr($avatar, 'http')) {
                $avatar = env('IMAGE_DOMAIN').$avatar;
            }
        }
        $data = [
            'platform' => $platform,
            'avatar' => $avatar,
            'nickname' => $nickName,
            'inviteurl' => $inviteUrl
        ];
        return view('mobile.mycenter.recommend', $data);
    }
    //商家入驻
    public function shopJoinIn() {
        return view('mobile.mycenter.shop_join_in');
    }
    //意见反馈
    public function suggestion() {
        return view('mobile.mycenter.suggestion');
    }
    //添加意见反馈
    public function addSuggestion() {
        $user = Auth::user();
        $userId = $user->id;
        $userName = $user->username;
        $mobile = $user->mobile;
        $content = $this->request->get('content');
        $result = MyCenter::addFeedback($userId, $content, $userName, $mobile);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //下载app
    public function download() {
        if($this->request->has('platform')) {
            $platform = $this->request->get('platform');
        } else {
            $platform = 'web'; //默认是web端
        }
        $system = '';
        $userAgent = $this->request->header('user-agent');
        if(strstr($userAgent, "FBWiOSApp")) {
            $platform = "iOS";
        } elseif(strstr($userAgent, "FBWAndroidApp")) {
            $platform = "Android";
        } elseif(stripos($userAgent, 'Android')) {
            $platform = 'Android';
        } elseif(stripos($userAgent, "iphone")) {
            $platform = "iOS";
        } elseif(stripos($userAgent, "ipad")) {
            $platform = "iOS";
        }
        if(stripos($userAgent, 'MicroMessenger')) {
            $isWeiXin = '1';
        } else {
            $isWeiXin = '0';
        }
        $androidDownloadUrl = 'http://file.fbw-china.com/download/fbw.apk';
        if(env('WEB_URL') == 'https://test2.fbw-china.com/') {
            $iosDownloadUrl = 'https://itunes.apple.com/app/apple-store/id1172353317?pt=118361877&ct=fbwp&mt=8';
        } else {
            $iosDownloadUrl = 'https://itunes.apple.com/cn/app/id1172353317'; //TODO ios 下载
        }
        $data = [
            'system' => $system,
            'platform' => $platform,
            'isweixin' => $isWeiXin,
            'iosdownloadurl' => $iosDownloadUrl,
            'androiddownloadurl' => $androidDownloadUrl,
        ];
        return view('mobile.mycenter.download', $data);
    }
    //用户协议
    public function userAgreement() {
        return view('mobile.mycenter.user_agreement');
    }
    //用户协议
    public function agreement() {
        return view('mobile.agreement');
    }
    //常见问题
    public function question() {
        return view('mobile.mycenter.question');
    }
    public function test() {
        $result = Common::isHoliday(date('Ymd'));
        dd($result);
    }
}